import 'dart:convert';

/// 目录信息模型
class Directory {
  final int id;
  final String name;
  final int? parentId; // 父目录ID，null表示没有父目录
  final int userId; // 用户ID
  final String path; // 目录完整路径
  final DateTime createTime;
  final DateTime updateTime;
  final bool isDeleted;
  final int? fileCount; // 文件数量，可选字段
  final List<Directory>? children; // 子目录，可选字段

  Directory({
    required this.id,
    required this.name,
    this.parentId,
    required this.userId,
    required this.path,
    required this.createTime,
    required this.updateTime,
    required this.isDeleted,
    this.fileCount,
    this.children,
  });

  /// 从JSON构造目录对象
  factory Directory.fromJson(Map<String, dynamic> json) {
    List<Directory>? childrenList;
    if (json['children'] != null) {
      childrenList = List<Directory>.from(
        (json['children'] as List).map((child) => Directory.fromJson(child)),
      );
    }

    return Directory(
      id: json['id'],
      name: json['name'],
      parentId: json['parent_id'],
      userId: json['user_id'],
      path: json['path'],
      createTime: DateTime.parse(json['create_time']),
      updateTime: DateTime.parse(json['update_time']),
      isDeleted: json['is_deleted'] ?? false,
      fileCount: json['file_count'],
      children: childrenList,
    );
  }

  /// 将目录对象转换为JSON
  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = {
      'id': id,
      'name': name,
      'parent_id': parentId,
      'user_id': userId,
      'path': path,
      'create_time': createTime.toIso8601String(),
      'update_time': updateTime.toIso8601String(),
      'is_deleted': isDeleted,
    };

    if (fileCount != null) {
      data['file_count'] = fileCount;
    }

    if (children != null) {
      data['children'] = children!.map((child) => child.toJson()).toList();
    }

    return data;
  }

  /// 从JSON字符串解析目录对象
  static Directory fromJsonString(String jsonString) {
    return Directory.fromJson(json.decode(jsonString));
  }

  /// 将目录对象转换为JSON字符串
  String toJsonString() {
    return json.encode(toJson());
  }

  /// 创建目录对象的副本
  Directory copyWith({
    int? id,
    String? name,
    int? parentId,
    int? userId,
    String? path,
    DateTime? createTime,
    DateTime? updateTime,
    bool? isDeleted,
    int? fileCount,
    List<Directory>? children,
  }) {
    return Directory(
      id: id ?? this.id,
      name: name ?? this.name,
      parentId: parentId ?? this.parentId,
      userId: userId ?? this.userId,
      path: path ?? this.path,
      createTime: createTime ?? this.createTime,
      updateTime: updateTime ?? this.updateTime,
      isDeleted: isDeleted ?? this.isDeleted,
      fileCount: fileCount ?? this.fileCount,
      children: children ?? this.children,
    );
  }
}
